package kt.com.bilin.coin.ui.activity

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import com.baidu.idl.face.platform.FaceSDKManager
import com.baidu.idl.face.platform.FaceStatusEnum
import com.baidu.idl.face.platform.LivenessTypeEnum
import com.baidu.idl.face.platform.ui.FaceLivenessActivity
import com.baidu.idl.face.platform.utils.Base64Utils
import kt.com.bilin.coin.common.toastMessageLong
import kt.com.bilin.coin.utils.Logger
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*

class OfflineFaceLivenessActivity : FaceLivenessActivity() {
    companion object {
        private const val licenseID = "CSJBL-face-android"
        private const val licenseFileName = "idl-license.face-android"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initFaceSDK()
    }

    private fun initFaceSDK() {
        FaceSDKManager.getInstance().initialize(this, licenseID, licenseFileName)
        setFaceConfig()
    }

    private fun setFaceConfig() {
        val config = FaceSDKManager.getInstance().faceConfig
        config.setLivenessRandom(true)
        config.setLivenessTypeList(mutableListOf(LivenessTypeEnum.HeadLeft, LivenessTypeEnum.Mouth, LivenessTypeEnum.Eye))
        FaceSDKManager.getInstance().faceConfig = config
        /*val console_config: ConsoleConfig = ConsoleJsonConfig.getInstance(this).getConfig()
        val config = FaceSDKManager.getInstance().faceConfig
        // SDK初始化已经设置完默认参数（推荐参数），您也根据实际需求进行数值调整
        val livenessList: MutableList<LivenessTypeEnum> = ArrayList()
        livenessList.add(LivenessTypeEnum.Mouth)
        livenessList.add(LivenessTypeEnum.Eye)
        // livenessList.add(LivenessTypeEnum.HeadUp);
        // livenessList.add(LivenessTypeEnum.HeadDown);
        // livenessList.add(LivenessTypeEnum.HeadLeft);
        // livenessList.add(LivenessTypeEnum.HeadRight);
        config.setLivenessTypeList(console_config.getActions(livenessList))

        // 设置 活体动作是否随机 boolean
        config.setLivenessRandom(console_config.isFaceVerifyRandom(true))
        // 模糊度范围 (0-1) 推荐小于0.7
        config.setBlurnessValue(console_config.getBlur(FaceEnvironment.VALUE_BLURNESS))
        // 光照范围 (0-1) 推荐大于40
        config.setBrightnessValue(console_config.getIllumination(FaceEnvironment.VALUE_BRIGHTNESS))
        config.setOcclusionValue(console_config.getOcclusion(FaceEnvironment.VALUE_OCCLUSION))

        // 裁剪人脸大小
        config.setCropFaceValue(FaceEnvironment.VALUE_CROP_FACE_SIZE)
        // 人脸yaw,pitch,row 角度，范围（-45，45），推荐-15-15
        config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH)
        config.setHeadRollValue(FaceEnvironment.VALUE_HEAD_ROLL)
        config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW)
        // 最小检测人脸（在图片人脸能够被检测到最小值）80-200， 越小越耗性能，推荐120-200
        config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE)
        // 人脸置信度（0-1）推荐大于0.6
        config.setNotFaceValue(0.2f)
        // 人脸遮挡范围 （0-1） 推荐小于0.5
        // 是否进行质量检测
        config.setCheckFaceQuality(console_config.isCheckLocalImageQuality(true))

        // 人脸检测使用线程数
        // config.setFaceDecodeNumberOfThreads(4);
        // 是否开启提示音
        config.setSound(true)
        FaceSDKManager.getInstance().faceConfig = config*/
    }

    override fun onLivenessCompletion(status: FaceStatusEnum?, message: String?, base64ImageMap: HashMap<String, String>?) {
        super.onLivenessCompletion(status, message, base64ImageMap)
        if (status == FaceStatusEnum.OK && mIsCompletion) {
            saveImage(base64ImageMap);
        } else if (status == FaceStatusEnum.Error_DetectTimeout ||
                status == FaceStatusEnum.Error_LivenessTimeout ||
                status == FaceStatusEnum.Error_Timeout) {
            "活体检测采集超时".toastMessageLong()
            finish()
            // Toast.makeText(this, "活体检测采集超时", Toast.LENGTH_SHORT).show();
            //alertText("检测结果", "活体检测采集超时");
        }
    }

    private fun saveImage(base64ImageMap: HashMap<String, String>?) {
        var bestImagePath = ""
        try {
            base64ImageMap?.let {
                val bestimageBase64 = it["bestImage0"] ?: ""
                val bmp: Bitmap = base64ToBitmap(bestimageBase64)
                val file = File.createTempFile("face", ".jpg")
                val outputStream = FileOutputStream(file)
                bmp.compress(Bitmap.CompressFormat.JPEG, 80, outputStream)
                outputStream.close()
                bestImagePath = file.absolutePath
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        setResult(RESULT_OK, Intent().apply { putExtra("bestimage_path", bestImagePath) })
        finish()
    }

    private fun base64ToBitmap(base64Data: String): Bitmap {
        val bytes = Base64Utils.decode(base64Data, Base64Utils.NO_WRAP)
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    }
}